<?php

namespace Xin\Setting;

use Xin\Setting\Contracts\Serializer as SerializerContracts;
use Xin\Support\Arr;

class Serializer implements SerializerContracts
{

	public function serialize($type, $value)
	{
		if ($type === 'object') {
			$value = json_encode($value, JSON_FORCE_OBJECT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
		}

		return $value;
	}

	public function unserialize($type, $value, &$isChange = null)
	{
		$isChange = true;

		if ($type == 'array') {
			return Arr::parse($value);
		} elseif ($type == 'switch') {
			return (int)$value;
		} elseif ($type == 'object') {
			return json_decode($value, true);
		} elseif ($type === 'number') {
			return is_int($value) || $value === '' || $value === null ? (int)$value : (float)$value;
		}

		$isChange = false;

		return $value;
	}
}
